package com.injurydetection.www.util.datautil;

import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.util.Log;

import com.kongqw.serialportlibrary.SerialPort;
import com.kongqw.serialportlibrary.SerialPortManager;
import com.kongqw.serialportlibrary.listener.OnOpenSerialPortListener;
import com.kongqw.serialportlibrary.listener.OnSerialPortDataListener;
import com.kongqw.serialportlibrary.thread.SerialPortReadThread;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by sunguiyong on 2020/9/1
 */
public class SerialPortManager1 extends SerialPort {
    private static final String TAG = "SerialPortManager1";
    private FileInputStream mFileInputStream;
    private FileOutputStream mFileOutputStream;
    private FileDescriptor mFd;
    private OnOpenSerialPortListener1 mOnOpenSerialPortListener1;
    private OnSerialPortDataListener1 mOnSerialPortDataListener1;
    private HandlerThread mSendingHandlerThread;
    private Handler mSendingHandler;
    private SerialPortReadThread1 mSerialPortReadThread;

    boolean chmod777(File file) {
        if (null != file && file.exists()) {
            try {
                Process su = Runtime.getRuntime().exec("/system/bin/su");
                String cmd = "chmod 777 " + file.getAbsolutePath() + "\nexit\n";
                su.getOutputStream().write(cmd.getBytes());
                if (0 == su.waitFor() && file.canRead() && file.canWrite() && file.canExecute()) {
                    return true;
                }
            } catch (InterruptedException | IOException var4) {
                var4.printStackTrace();
            }

            return false;
        } else {
            return false;
        }
    }

    public SerialPortManager1() {
    }

    public boolean openSerialPort(File device, int baudRate) {
        Log.i(TAG, "openSerialPort: " + String.format("打开串口 %s  波特率 %s", device.getPath(), baudRate));
        if (!device.canRead() || !device.canWrite()) {
            boolean chmod777 = this.chmod777(device);
            if (!chmod777) {
                Log.i(TAG, "openSerialPort: 没有读写权限");
                if (null != this.mOnOpenSerialPortListener1) {
                    this.mOnOpenSerialPortListener1.onFail(device, OnOpenSerialPortListener.Status.NO_READ_WRITE_PERMISSION);
                }

                return false;
            }
        }

        try {
            this.mFd = this.open(device.getAbsolutePath(), baudRate, 0);
            this.mFileInputStream = new FileInputStream(this.mFd);
            this.mFileOutputStream = new FileOutputStream(this.mFd);
            Log.i(TAG, "openSerialPort1: 串口已经打开哈哈 " + this.mFd);
            if (null != this.mOnOpenSerialPortListener1) {
                this.mOnOpenSerialPortListener1.onSuccess(device);
            }

            this.startSendThread();
            this.startReadThread();
            return true;
        } catch (Exception var4) {
            var4.printStackTrace();
            if (null != this.mOnOpenSerialPortListener1) {
                this.mOnOpenSerialPortListener1.onFail(device, OnOpenSerialPortListener.Status.OPEN_FAIL);
            }

            return false;
        }
    }

    public void closeSerialPort() {
        if (null != this.mFd) {
            this.close();
            this.mFd = null;
        }

        this.stopSendThread();
        this.stopReadThread();
        if (null != this.mFileInputStream) {
            try {
                this.mFileInputStream.close();
            } catch (IOException var3) {
                var3.printStackTrace();
            }

            this.mFileInputStream = null;
        }

        if (null != this.mFileOutputStream) {
            try {
                this.mFileOutputStream.close();
            } catch (IOException var2) {
                var2.printStackTrace();
            }

            this.mFileOutputStream = null;
        }

        this.mOnOpenSerialPortListener1 = null;
        this.mOnSerialPortDataListener1 = null;
    }

    public SerialPortManager1 setOnOpenSerialPortListener(OnOpenSerialPortListener1 listener) {
        this.mOnOpenSerialPortListener1 = listener;
        return this;
    }

    public SerialPortManager1 setOnSerialPortDataListener(OnSerialPortDataListener1 listener) {
        this.mOnSerialPortDataListener1 = listener;
        return this;
    }

    private void startSendThread() {
        this.mSendingHandlerThread = new HandlerThread("mSendingHandlerThread");
        this.mSendingHandlerThread.start();
        this.mSendingHandler = new Handler(this.mSendingHandlerThread.getLooper()) {
            public void handleMessage(Message msg) {
                byte[] sendBytes = (byte[]) ((byte[]) msg.obj);
                if (null != SerialPortManager1.this.mFileOutputStream && null != sendBytes && 0 < sendBytes.length) {
                    try {
                        SerialPortManager1.this.mFileOutputStream.write(sendBytes);
                        if (null != SerialPortManager1.this.mOnSerialPortDataListener1) {
                            SerialPortManager1.this.mOnSerialPortDataListener1.onDataSent(sendBytes);
                        }
                    } catch (IOException var4) {
                        var4.printStackTrace();
                    }
                }

            }
        };
    }

    private void stopSendThread() {
        this.mSendingHandler = null;
        if (null != this.mSendingHandlerThread) {
            this.mSendingHandlerThread.interrupt();
            this.mSendingHandlerThread.quit();
            this.mSendingHandlerThread = null;
        }

    }

    private void startReadThread() {
        this.mSerialPortReadThread = new SerialPortReadThread1(this.mFileInputStream) {
            public void onDataReceived(byte[] bytes) {
                if (null != SerialPortManager1.this.mOnSerialPortDataListener1) {
                    SerialPortManager1.this.mOnSerialPortDataListener1.onDataReceived(bytes);
                }

            }
        };
        this.mSerialPortReadThread.start();
    }

    private void stopReadThread() {
        if (null != this.mSerialPortReadThread) {
            this.mSerialPortReadThread.release();
        }

    }

    public boolean sendBytes(byte[] sendBytes) {
        if (null != this.mFd && null != this.mFileInputStream && null != this.mFileOutputStream && null != this.mSendingHandler) {
            Message message = Message.obtain();
            message.obj = sendBytes;
            return this.mSendingHandler.sendMessage(message);
        } else {
            return false;
        }
    }
}
